﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JsonParser
{
	public class JsonString : JsonValue
	{
		private TrimmableIndexString _baseValue;

		private JsonString(TrimmableIndexString value)
		{
			this._baseValue = value.Substring(1, value.Length - 2);
		}

		public static new JsonString Parse(TrimmableIndexString value)
		{
			if (value[0] != '"')
			{
				throw new InvalidJsonException("A Json string must start with a \".");
			}

			for (int i = 1; i < value.Length; i++)
			{
				switch (value[i])
				{
					case '"':
						return new JsonString(value.Substring(0, ++i));
					case '\\':
						i++;
						switch (value[i])
						{
							case '"':
							case '\\':
							case '/':
							case 'b':
							case 'f':
							case 'n':
							case 'r':
							case 't':
								break;
							case 'u':
								for (int u = 0; u < 4; u++)
								{
									i++;
									if (!('0' <= value[i] && value[i] <= '9' || 'a' <= value[i] && value[i] <= 'f' || 'A' <= value[i] && value[i] <= 'F'))
									{
										throw new InvalidJsonException(string.Format("'{0}' is an invalid hexidecimal digit.", value[i]));
									}
								}
								break;
							default:
								throw new InvalidJsonException(string.Format("\"\\{0}\" is an invalid escape sequence.", value[i]));
						}
						break;
					default:
						break;
				}
			}

			throw new InvalidJsonException("The end of the source value was reached without finding an unescaped \".");
		}
	}
}
